package com.sz.virtualbank.web.controller.finance;

import java.math.BigDecimal;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sz.virtualbank.common.annotation.LoginRequired;
import com.sz.virtualbank.common.result.CommonResponse;
import com.sz.virtualbank.dao.entity.FinancialProduct;
import com.sz.virtualbank.dao.entity.InvestmentOrder;
import com.sz.virtualbank.dao.entity.User;
import com.sz.virtualbank.service.finance.FinanceService;
import com.sz.virtualbank.service.user.UserService;
import com.sz.virtualbank.web.vo.finance.PurchaseProductReqVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;

/**
 * 理财产品相关接口
 *
 * @author Claude
 */
@RestController
@RequestMapping("/api/finance")
@Slf4j
@Api(tags = "理财产品接口")
public class FinancialProductController {

    @Autowired
    private FinanceService financeService;

    @Autowired
    private UserService userService;

    /**
     * 查询理财产品列表
     */
    @GetMapping("/product/list")
    @ApiOperation("查询理财产品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "riskLevel", value = "风险等级", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "minDuration", value = "最小投资期限", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "maxDuration", value = "最大投资期限", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "minReturn", value = "最小预期收益率", dataType = "BigDecimal", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "产品状态", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "Integer", paramType = "query", required = true)
    })
    public CommonResponse<Map<String, Object>> getProductList(
            @RequestParam(required = false) Integer riskLevel,
            @RequestParam(required = false) Integer minDuration,
            @RequestParam(required = false) Integer maxDuration,
            @RequestParam(required = false) BigDecimal minReturn,
            @RequestParam(required = false) Integer status,
            @RequestParam Integer page,
            @RequestParam Integer size) {

        Map<String, Object> result = financeService.getProductList(
                riskLevel, minDuration, maxDuration, minReturn, status, page, size);
        return CommonResponse.success(result);
    }

    /**
     * 查询理财产品详情
     */
    @GetMapping("/product/{id}")
    @ApiOperation("查询理财产品详情")
    public CommonResponse<FinancialProduct> getProductDetail(@PathVariable Long id) {
        FinancialProduct product = financeService.getProductDetail(id);
        return CommonResponse.success(product);
    }

    /**
     * 查询热门理财产品
     */
    @GetMapping("/product/hot")
    @ApiOperation("查询热门理财产品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limit", value = "查询数量", dataType = "Integer", paramType = "query")
    })
    public CommonResponse<Map<String, Object>> getHotProducts(@RequestParam(required = false) Integer limit) {
        Map<String, Object> result = financeService.getHotProducts(limit);
        return CommonResponse.success(result);
    }

    /**
     * 购买理财产品
     */
    @PostMapping("/product/purchase")
    @ApiOperation("购买理财产品")
    @LoginRequired
    public CommonResponse<InvestmentOrder> purchaseProduct(@RequestBody @Valid PurchaseProductReqVO reqVO,
                                                           HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        User user = userService.getCurrentUser(token);

        InvestmentOrder order = financeService.purchaseProduct(user.getId(),
                reqVO.getProductId(), reqVO.getAmount(), reqVO.getPaymentPassword());

        return CommonResponse.success(order);
    }

    /**
     * 查询投资订单列表
     */
    @GetMapping("/order/list")
    @ApiOperation("查询投资订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "订单状态", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "Integer", paramType = "query", required = true)
    })
    @LoginRequired
    public CommonResponse<Map<String, Object>> getInvestmentOrderList(
            @RequestParam(required = false) Integer status,
            @RequestParam Integer page,
            @RequestParam Integer size,
            HttpServletRequest request) {

        String token = request.getHeader("Authorization").replace("Bearer ", "");
        User user = userService.getCurrentUser(token);

        Map<String, Object> result = financeService.getInvestmentOrderList(user.getId(), status, page, size);
        return CommonResponse.success(result);
    }

    /**
     * 查询投资订单详情
     */
    @GetMapping("/order/{id}")
    @ApiOperation("查询投资订单详情")
    @LoginRequired
    public CommonResponse<Map<String, Object>> getInvestmentOrderDetail(@PathVariable Long id,
                                                                        HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        User user = userService.getCurrentUser(token);

        Map<String, Object> result = financeService.getInvestmentOrderDetail(id, user.getId());
        return CommonResponse.success(result);
    }

    /**
     * 查询投资统计信息
     */
    @GetMapping("/summary")
    @ApiOperation("查询投资统计信息")
    @LoginRequired
    public CommonResponse<Map<String, BigDecimal>> getInvestmentSummary(HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        User user = userService.getCurrentUser(token);

        Map<String, BigDecimal> result = financeService.getInvestmentSummary(user.getId());
        return CommonResponse.success(result);
    }

    /**
     * 新增理财产品（管理员接口）
     */
    @PostMapping("/product/create")
    @ApiOperation("新增理财产品")
    @LoginRequired
    public CommonResponse<FinancialProduct> createProduct(@RequestBody FinancialProduct product) {
        // TODO: 实际应用中需要进行管理员权限校验

        FinancialProduct result = financeService.createProduct(product);
        return CommonResponse.success(result);
    }

    /**
     * 更新理财产品（管理员接口）
     */
    @PutMapping("/product/update")
    @ApiOperation("更新理财产品")
    @LoginRequired
    public CommonResponse<FinancialProduct> updateProduct(@RequestBody FinancialProduct product) {
        // TODO: 实际应用中需要进行管理员权限校验

        FinancialProduct result = financeService.updateProduct(product);
        return CommonResponse.success(result);
    }

    /**
     * 更新产品状态（管理员接口）
     */
    @PutMapping("/product/status/{id}")
    @ApiOperation("更新产品状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "产品ID", dataType = "Long", paramType = "path", required = true),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "Integer", paramType = "query", required = true)
    })
    @LoginRequired
    public CommonResponse<Boolean> updateProductStatus(@PathVariable Long id, @RequestParam Integer status) {
        // TODO: 实际应用中需要进行管理员权限校验

        boolean result = financeService.updateProductStatus(id, status);
        return CommonResponse.success(result);
    }
}
